<template>
    <el-card v-loading="loading">
        <div slot="header">
            {{isCreate ? '创建账号' : '编辑 '+form.username}}
        </div>
        <el-form :model="form" :rules="rules" ref="userForm" label-width="100px">
            <el-form-item label="账号" prop="username">
                <el-input v-model="form.username" auto-complete="off" placeholder="可以填入中文，最少2位"/>
            </el-form-item>
            <el-form-item label="手机号码" prop="phone">
                <el-input v-model="form.phone" auto-complete="off" placeholder="11位手机号码"/>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
                <el-input v-model="form.email" placeholder="邮箱地址"/>
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-input type="password" v-model="form.password" auto-complete="off"
                          placeholder="最少6位"/>
            </el-form-item>
            <el-form-item label="确认密码" prop="checkPassword">
                <el-input type="password" v-model="form.checkPassword" auto-complete="off"
                          placeholder="确认密码一致性"/>
                <el-alert type="warning" title="不修改密码，请将两个密码输入框留空"/>
            </el-form-item>
            <el-form-item label="禁止登录到">
                <el-date-picker v-model="form.disable" type="datetime"/>
                <br>时间到期后可登录
            </el-form-item>
            <el-form-item>
                <my-alert ref="alert"/>
                <el-button type="primary" @click="submit" :loading="submitting">提交</el-button>
                <el-button @click="$router.push('/user')">返回账号列表</el-button>
            </el-form-item>
        </el-form>
    </el-card>
</template>

<script>
    import MyAlert from "../component/my_alert";

    export default {
        components: {MyAlert},
        data() {
            return {
                loading: false,
                submitting: false,
                form: {
                    id: 0,
                    username: '',
                    email: '',
                    phone: '',
                    password: '',
                    checkPassword: '',
                    disable: ''
                },
                rules: {
                    username: [{
                        required: true, trigger: 'blur', validator(rule, value, cb) {
                            if (!value || value.length < 2)
                                return cb(new Error('最少输入两个字符'));
                            cb();
                        },
                    }],
                    email: [{required: true, type: 'email', message: '请填写正确的邮箱', trigger: 'blur',}],
                    phone: [{
                        validator(rule, value, cb) {
                            if (/^1\d{10}$/.test(value))
                                return cb();
                            cb(new Error('请填写正确的手机号码'));
                        }, required: true, trigger: 'blur,change',
                    }],
                    password: [{
                        validator: (rule, value, cb) => {
                            if (_.isEmpty(value) && !this.isCreate)
                                return cb();
                            if (!value || value.length < 6)
                                return cb(new Error('密码长度最少需要6个字符'));
                            cb();
                        },
                        required: true, trigger: 'blur,change',
                    }],
                    checkPassword: [{
                        validator: (rule, value, cb) => {
                            if (value !== this.form.password)
                                return cb(new Error('两个密码不相同'));
                            cb();
                        },
                        required: true, trigger: 'blur',
                    }],
                },
            };
        },
        methods: {
            fetch(user_id) {
                this.loading = true;
                this.$http.get('/api/user/' + user_id).then(({data}) => {
                    this.loading = false;
                    this.form = data;
                }).catch(err => {
                    this.$router.replace('/404');
                });
            },
            submit() {
                this.$refs['userForm'].validate(valid => {
                    if (!valid) return;
                    this.submitting = true;
                    this.$http.post('/api/user/', this.form).then(res => {
                        if (this.isCreate) {
                            this.$refs['alert'].success('成功创建账号，请等待跳转');
                            setTimeout(() => {
                                this.$router.push('/user/' + res.data.id + '/edit');
                            }, 1000);
                            return;
                        }
                        this.submitting = false;
                        this.$refs['alert'].success(res.data);
                    }).catch(res => {
                        this.submitting = false;
                        this.$refs['alert'].error(res.response.data);
                    });
                });
            }
        },
        computed: {
            isCreate() {
                return this.form && this.form.id === 0;
            }
        },
        mounted() {
            if (this.$store.state.user.level.id > 2 || this.$route.params.id == 1)
                this.$router.replace('/403');

            if (this.$route.params.id > 0)
                this.fetch(this.$route.params.id);
            else
                this.loading = false;

            this.rules.password[0].required = !(this.$route.params.id > 0);
            this.rules.checkPassword[0].required = !(this.$route.params.id > 0);
        }
    }
</script>

<style scoped>

</style>